/*
* Copyright 2007 University of Oxford
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

var CG_ISSUE_ID_PREFIX = "issue_";
var CG_GOOGLECODE_URL = "http://code.google.com";

////////////////////////////////////////////////////////////////////////////////
// Preferences
////////////////////////////////////////////////////////////////////////////////

var CG_prefManager = Components.classes["@mozilla.org/preferences-service;1"]
                                .getService(Components.interfaces.nsIPrefBranch);

////////////////////////////////////////////////////////////////////////////////
// Initialisation
////////////////////////////////////////////////////////////////////////////////

var CG_projects = new Array();
var CG_currentProject = new Project();


var CG_issues = new Array();
var CG_currentIssue = new Issue();
                               
window.addEventListener("load", function(e) { CG_init(); }, false); 

function CG_init() {
    var projectsListJSON = CG_prefManager.getCharPref("extensions.codegoo.projects");
    CG_projects = projectsListJSON.parseJSON();
   
    //load current project
    var project = document.getElementById('selectedProject').label;    
    CG_currentProject = project;
    CG_selectProject(document.getElementById('selectedProject').label);
}

////////////////////////////////////////////////////////////////////////////////
// XUL functions
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
// Places dynamically generated menu items inside our main meny
////////////////////////////////////////////////////////////////////////////////
function CG_mainMenuPopulate() {
    var menu = document.getElementById("projectsMenu");

    for(var i=menu.childNodes.length - 1; i >= 0; i--) {
        menu.removeChild(menu.childNodes.item(i));
    }
    
    for (i = 0; i < CG_projects.length; i++) {
        var project = CG_projects[i];
        var tempItem = document.createElement("menuitem");
        tempItem.setAttribute("id", "project " + i);
        tempItem.setAttribute("label", project.name);
        tempItem.addEventListener("command", CG_projectSelected, true);
        menu.appendChild(tempItem);
    }
    
    tempItem =  document.createElement("menuseparator");
    menu.appendChild(tempItem);
    
    tempItem =  document.createElement("menuitem");
    tempItem.setAttribute("id", "addProject");
    tempItem.setAttribute("label", "Add Project");
    tempItem.addEventListener("command", CG_addProject, true);
    menu.appendChild(tempItem);
    
    tempItem =  document.createElement("menuitem");
    tempItem.setAttribute("id", "removeProject");
    tempItem.setAttribute("label", "Remove Project");
    tempItem.addEventListener("command", CG_removeProject, true);
    menu.appendChild(tempItem);
}

///////////////////////////////////////////////////////////////////////////////
// Populate the Search menu button
//
///////////////////////////////////////////////////////////////////////////////

function CG_searchMenuPopulate() {
    var menu = document.getElementById("projectSearch");
    
    for(var i=menu.childNodes.length - 1; i >= 0; i--) {
        menu.removeChild(menu.childNodes.item(i));
    }

    // if the loaded project is a Google Project then display this menu
    if (CG_currentProject.baseURL == "http://code.google.com/p/") {
        var tempItem =  document.createElement("menuitem");
        tempItem.setAttribute("id", "searchIssues");
        tempItem.setAttribute("label", "Issues");
        tempItem.setAttribute("tooltiptext", "Search Issues");
        tempItem.addEventListener("command", CG_loadIssueListPage, true);
        menu.appendChild(tempItem);
    
        tempItem =  document.createElement("menuitem");
        tempItem.setAttribute("id", "searchWiki");
        tempItem.setAttribute("label", "Wiki");
        tempItem.setAttribute("tooltiptext", "Search Wiki");
        tempItem.setAttribute("oncommand", "CG_loadWikiPage(document.getElementById('selectedProject').label)");
        menu.appendChild(tempItem);    
    
        tempItem =  document.createElement("menuitem");
        tempItem.setAttribute("id", "searchSVN");
        tempItem.setAttribute("label", "SVN");
        tempItem.setAttribute("tooltiptext", "Search SVN");
        tempItem.setAttribute("oncommand", "CG_loadSVNPage(document.getElementById('selectedProject').label)");
        menu.appendChild(tempItem);    
   }
   // if the project is hosted on SourceForge then display this menu
   else if (CG_currentProject.baseURL == "http://sourceforge.net/projects/") {
        var tempItem =  document.createElement("menuitem");
        tempItem.setAttribute("id", "searchTracker");
        tempItem.setAttribute("label", "Tracker");
        tempItem.setAttribute("tooltiptext", "Search the Tracker");
        tempItem.addEventListener("command", CG_searchTrackerSourceForge, true);
        menu.appendChild(tempItem);  
        
        tempItem =  document.createElement("menuitem");
        tempItem.setAttribute("id", "searchForum");
        tempItem.setAttribute("label", "Forum");
        tempItem.setAttribute("tooltiptext", "Search the Forum");
        tempItem.addEventListener("command", CG_searchForumSourceForge, true);
        menu.appendChild(tempItem);     
        
        tempItem =  document.createElement("menuitem");
        tempItem.setAttribute("id", "searchMailingList");
        tempItem.setAttribute("label", "Mailing List");
        tempItem.setAttribute("tooltiptext", "Search the Mailing List");
        tempItem.addEventListener("command", CG_searchMailingListSourceForge, true);
        menu.appendChild(tempItem);             
        
        tempItem =  document.createElement("menuitem");
        tempItem.setAttribute("id", "searchDocs");
        tempItem.setAttribute("label", "Documentation");
        tempItem.setAttribute("tooltiptext", "Search the Documentation");
        tempItem.addEventListener("command", CG_searchDocsSourceForge, true);
        menu.appendChild(tempItem);         
        
   }
   else {
        //do nothing if no project loaded
        var tempItem =  document.createElement("menuitem");
        tempItem.setAttribute("id", "selectProject");
        tempItem.setAttribute("label", "Select a Project!");
        tempItem.setAttribute("tooltiptext", "Please select a project");
        menu.appendChild(tempItem); 
   }
    
}


////////////////////////////////////////////////////////////////////////////////
// Populate the issues menu button, this provides easy access to issues in the
// curently selected project.
//
// Regex for getting table rows: table[@class="results"][@id="resultstable"]/tbody/tr
////////////////////////////////////////////////////////////////////////////////
function CG_issuesMenuPopulate() {
    var menu = document.getElementById("issuesMenu");

    for(var i=menu.childNodes.length - 1; i >= 0; i--) {
        menu.removeChild(menu.childNodes.item(i));
    }

    // if the loaded project is a Google Project then display this menu
    if (CG_currentProject.baseURL == "http://code.google.com/p/") {
      var tempItem =  document.createElement("menuitem");
      tempItem.setAttribute("id", "newIssueNavigation");
      tempItem.setAttribute("label", "New Issue");
      tempItem.setAttribute("tooltiptext", "Add a new issue to this project");
      tempItem.addEventListener("command", CG_loadNewIssuePage, true);
      menu.appendChild(tempItem);
  
      tempItem =  document.createElement("menuseparator");
      menu.appendChild(tempItem); 
  
      tempItem =  document.createElement("menuitem");
      tempItem.setAttribute("label", "Popular");
      tempItem.setAttribute("tooltiptext", "Filtered and sorted list of issues considered popular");
      tempItem.setAttribute("oncommand", "CG_listPopularIssues()");
      menu.appendChild(tempItem);
  
      tempItem =  document.createElement("menuitem");
      tempItem.setAttribute("label", "To Verify");
      tempItem.setAttribute("tooltiptext", "Filtered and sorted list of issues needing verification");
      tempItem.setAttribute("oncommand", "CG_listIssuesBySearchType('7')");
      menu.appendChild(tempItem);
  
      tempItem =  document.createElement("menuitem");
      tempItem.setAttribute("label", "New Issues");
      tempItem.setAttribute("tooltiptext", "Filtered and sorted list of new issues");
      tempItem.setAttribute("oncommand", "CG_listIssuesBySearchType('6')");
      menu.appendChild(tempItem);
  
      tempItem =  document.createElement("menuitem");
      tempItem.setAttribute("label", "Your starred");
      tempItem.setAttribute("tooltiptext", "Filtered and sorted list of issues you have starred");
      tempItem.setAttribute("oncommand", "CG_listIssuesBySearchType('5')");
      menu.appendChild(tempItem);
  
      tempItem =  document.createElement("menuitem");
      tempItem.setAttribute("label", "Your reported issues");
      tempItem.setAttribute("tooltiptext", "Filtered and sorted list of issues reported by you");
      tempItem.setAttribute("oncommand", "CG_listIssuesBySearchType('4')");
      menu.appendChild(tempItem);
  
      tempItem =  document.createElement("menuitem");
      tempItem.setAttribute("label", "Your assigned Issues");
      tempItem.setAttribute("tooltiptext", "Filtered and sorted list of issues assigned to you");
      tempItem.setAttribute("oncommand", "CG_listIssuesBySearchType('3')");
      menu.appendChild(tempItem);
  
      tempItem =  document.createElement("menuitem");
      tempItem.setAttribute("label", "All Issues");
      tempItem.setAttribute("tooltiptext", "Filtered and sorted list of all issues");
      tempItem.setAttribute("oncommand", "CG_listIssuesBySearchType('1')");
      menu.appendChild(tempItem);
  
      tempItem =  document.createElement("menuseparator");
      menu.appendChild(tempItem);  
    } 
        
    var issues = CG_currentProject.issues;    
    if (issues != null && issues.length > 0) {
        for (i = 0; i < issues.length; i ++) {
          menuissue = issues[i];
          tempItem =  document.createElement("menuitem");
          tempItem.setAttribute("id", CG_ISSUE_ID_PREFIX + menuissue.id);
          tempItem.setAttribute("label", "Issue: " + menuissue.description);
          tempItem.setAttribute("tooltiptext", menuissue.description);
          tempItem.addEventListener("command", CG_loadIssuePage, true);
          menu.appendChild(tempItem);
        }
        
        tempItem =  document.createElement("menuseparator");
        menu.appendChild(tempItem);
    }
    
    tempItem =  document.createElement("menuitem");
    tempItem.setAttribute("id", "addIssue");
    tempItem.setAttribute("label", "Add Issue to toolbar");
    tempItem.addEventListener("command", CG_addIssue, true);
    menu.appendChild(tempItem);
    
    tempItem =  document.createElement("menuitem");
    tempItem.setAttribute("id", "removeIssue");
    tempItem.setAttribute("label", "Remove Issue from toolbar");
    tempItem.addEventListener("command", CG_removeIssue, true);
    menu.appendChild(tempItem);
    
}

////////////////////////////////////////////////////////////////////////////////
// Load the issue relating to the one indicated in the selected
// menu item that fired the event
////////////////////////////////////////////////////////////////////////////////
function CG_loadIssuePage(event) {
  var url;  
  if (CG_currentProject.baseURL == "http://code.google.com/p/") {
    var project = document.getElementById('selectedProject').label;
    var id = event["target"]["id"].substring(CG_ISSUE_ID_PREFIX.length);
    url = CG_getBaseURL(project) + "/issues/detail?id=" + id;
  } else if (CG_currentProject.baseURL == "http://sourceforge.net/projects/") {
    var project = document.getElementById('selectedProject').label;
    var issueid = event["target"]["id"].substring(CG_ISSUE_ID_PREFIX.length);
    var currentAtid;
    try {
        var issues = CG_currentProject.issues; 
        for(var i = 0; i < issues.length ; i++) {
            if (issues[i].id == issueid) {
                currentAtid = CG_currentProject.issues[i].atid;
            }
        }
    } catch(err) {
      alert("error is " + err);
    }
    url = "http://sourceforge.net/tracker/?func=detail&aid=" + issueid + "&group_id=" + CG_currentProject.id + "&atid=" + currentAtid;
  }  
  CG_loadURL(url);

}

////////////////////////////////////////////////////////////////////////////////
// Add a project to the list of projects known by the toolbar.
// If the currently visible page is not a project page then an
// error is reported.
////////////////////////////////////////////////////////////////////////////////
function CG_addProject(event){
    var pageURL = gBrowser.currentURI.spec;
    var projectName = CG_getProjectName(pageURL);
    var sourceforgeName = CG_getSFName(pageURL);
    if (projectName != null) {
        var baseURL = "http://code.google.com/p/";
        var id = "00000";
        var projectType = "CG";
        var newProject = new Project(projectName, baseURL, id, projectType);         
        try {
          for(i=0; i < CG_projects.length; i++) {
            if (CG_projects[i].name == projectName) {
              alert("The '" + projectName + "' project is already in your collection.");
              return;
            }
          }
          CG_projects[CG_projects.length] = newProject;        
          CG_saveProjects();
          CG_createDoap(newProject);          
          CG_selectProject(newProject.name);
          alert("You have added the Google Code project " + projectName);
        }
        catch(err) {
          alert("error is " + err);
        }
        
    } else if (sourceforgeName != null){
        var baseURL = "http://sourceforge.net/projects/"; 
        var projectType = "SF";
        try{
          var atags = window._content.document.getElementsByTagName("a");
          for (var i = 0; i < atags.length ; i++) {
            re = RegExp("http://sourceforge.net/project/report_inappropriate.php\\?group_id=([0-9]*)");
            matches = re.exec(atags[i]);
            if (matches != null) {
                var id = matches[1]; 
            } 
          }
          if (id == null) {
            alert("You must be on the " + sourceforgeName + " home page to add this Source Forge project to your collection.");
          } 
        var newProject = new Project(sourceforgeName, baseURL, id, projectType);    
        } catch(err) {
          alert("You must be on the " + sourceforgeName + " home page to add this Source Forge project to your collection: "+ err);
        }
    
        for(i=0; i < CG_projects.length; i++) {
          if (CG_projects[i].name == sourceforgeName) {
            alert("The '" + sourceforgeName + "' project is already in your collection.");
            return;
          }
        }       
        CG_projects[CG_projects.length] = newProject;               
        CG_selectProject(newProject.name);
        CG_saveProjects();
        alert("You have added the SourceForge project, '" + sourceforgeName + "' to your collection.");
    } else {
        alert("You must be viewing the Google Code or Source Forge Home project page to be able to add it to your collection.");
    
    }
    
}


////////////////////////////////////////////////////////////////////////////////
// Save the current projects to the preference manager
////////////////////////////////////////////////////////////////////////////////
function CG_saveProjects() {
  CG_prefManager.setCharPref("extensions.codegoo.projects", CG_projects.toJSONString());
}

////////////////////////////////////////////////////////////////////////////////
// Save the current issues to the preference manager
////////////////////////////////////////////////////////////////////////////////
function CG_saveIssues() {
  CG_prefManager.setCharPref("extensions.codegoo.issues", CG_issues.toJSONString());
}

////////////////////////////////////////////////////////////////////////////////
// Remove the currently active project from the list of projects known 
// by the toolbar. 
////////////////////////////////////////////////////////////////////////////////
function CG_removeProject(event){
    var projectButton = document.getElementById("selectedProject");
    projectName = projectButton.label;
    
    conf = confirm("Delete the " + projectName + " project?")
    if(conf == true) {   
      var projects = [];
      for(i=0; i < CG_projects.length; i++) {
        if (CG_projects[i].name != projectName) {
          projects[projects.length] = CG_projects[i];
        }
      }
      CG_projects = projects;
      CG_prefManager.setCharPref("extensions.codegoo.projects", CG_projects.toJSONString());    
      CG_selectProject(CG_projects[0].name);
    }
}

////////////////////////////////////////////////////////////////////////////////
// Add an issue to the list of issues known by the toolbar for this project.
// If the currently visible page is not an issue page for the current project
// then an error is reported.
////////////////////////////////////////////////////////////////////////////////
function CG_addIssue(event){
    var pageURL = gBrowser.currentURI.spec; 
    var issueObj;
    var issueDescription;
    var issueId;
    var atid;
    //if the issue is for a Google Code project do the following
    if(CG_currentProject.projectType == "CG") {
      if (pageURL.indexOf(CG_getBaseURL(CG_currentProject.name)) != 0) {
        alert("To add an issue from your toolbar you need to be viewing its overview page." + pageURL.indexOf(CG_getBaseURL(CG_currentProject.name)) + CG_getBaseURL(CG_currentProject.name))
        return;
      }
    } else // if project is a Sourceforge one then get the atid and check the group/project id is stored
    {
      atid = CG_getIssueAtid(pageURL);
      if(CG_currentProject.id == null) {
      	// get group_id from url
      	CG_currentProject.id = CG_getIssueGroupid(pageURL);
      	if(CG_currentProject.id == null) {
      		alert("This is not a Sourceforge issue page.");
      		return;
   		}
      }
    }
    try{ 
    	issueId = CG_getIssueID(pageURL, CG_currentProject.projectType);  
    }
    catch(err)
    {
    	alert(err);
    }
    try{
      //check for description of issues
      var tags = CG_getIssueDescription();
      var y = tags.childNodes[0]
      issueDescription = y.nodeValue;
    }catch(err) { 
      alert(err);
    }
    try {
     issueObj = new Issue(issueId, issueId, issueDescription, atid);
    }
    catch(err) {
     alert("error is " + err);
    }
    try{
    if (issueId != null) { 
      if (CG_currentProject.issues != null && CG_currentProject.issues.toJSONString().indexOf(issueObj.toJSONString()) >= 0) {
          alert("Issue number " + issueObj.id + " is already in your collection");
          return;
      }    
      if (CG_currentProject.issues == null) {
        CG_currentProject.issues = new Array();
      }
      //adds issue to CG_currentProject at end of array
      CG_currentProject.issues.push(issueObj);
      CG_saveProjects(); 
      alert("Issue:- \n" + issueDescription + "\n has been added to your toolbar.");
    }
    else {
        alert("You must be viewing an issue page for the " + CG_currentProject.name + " project.");
    }
    } catch(err) {
    	alert(err);
    }
}


function CG_getIssueDescription() {
    var titleTags = window._content.document.getElementsByTagName("title")[0];
    return titleTags;        
}

////////////////////////////////////////////////////////////////////////////////
// Removes an issue from the list of issues known by the toolbar for this project.
// If the currently visible page is not an issue page for the current project in the
// toolbar then an error is reported.
////////////////////////////////////////////////////////////////////////////////
function CG_removeIssue(event) {
    var pageURL = gBrowser.currentURI.spec;
    issueId = CG_getIssueID(pageURL, CG_currentProject.projectType);    
    //check url is an issue page
    if (issueId != null) {    
        // check if the issue is listed in your current project 
        var currentProject = CG_currentProject;
        try{
            var issueIsInCollection = new Boolean(false);
            for(var i=0; i < currentProject.issues.length; i++) {
                if (issueId == currentProject.issues[i].id) {
                    issueIsInCollection = new Boolean(true); 
                    var issueDescription = currentProject.issues[i].description;         
                    conf = confirm("Delete the issue? \n" + issueDescription);
                    if(conf == true) {          
                        // now we can remove the issue! Splice it!
                        currentProject.issues.splice(i,1);        
                        CG_currentProject = currentProject; 
                        CG_saveProjects();
                        alert("The issue " + issueDescription + " has been deleted." );  
                    }       
                }
            }
        } catch(err) {
            alert(err);
        }
        if(issueIsInCollection.toString() == "false") {
            alert("This issue is not in your toolbar so you cannot remove it!");  
        }
    } else {
        alert("You must be viewing an issue page for the " + CG_currentProject.name + " project that has been added to your toolbar.");
    }
}

////////////////////////////////////////////////////////////////////////////////
// Attempts to extract a project name from the supplied Code Google URL.
// If the url is not from a known Google Code project page then null is returned.
////////////////////////////////////////////////////////////////////////////////
function CG_getProjectName(url) {
    re = RegExp("http://code.google.com/p/([^/.]*)/.*");
    matches = re.exec(url);
    if (matches == null || matches.length < 2) {
        return null;
    }
    return matches[1];
}

////////////////////////////////////////////////////////////////////////////////
// Attempts to extract a project name from the supplied Sourceforge URL.
// If the url is not from a known Sourceforge project page then null is returned.
////////////////////////////////////////////////////////////////////////////////
function CG_getSFName(url) {
    re = RegExp("http://sourceforge.net/projects/([^/.]*)/.*");
    matches = re.exec(url);
    if (matches == null || matches.length < 2) {
        return null;
    }
    //alert("Sourceforge name is "+ matches[1]);
    return matches[1];
}

////////////////////////////////////////////////////////////////////////////////
// Attempts to extract an issue ID from the supplied URL.
// If the url is not from a known issue page type then null is returned.
////////////////////////////////////////////////////////////////////////////////
function CG_getIssueID(url, projectType) {
	if(projectType == null) {
		if(CG_currentProject.baseURL == "http://sourceforge.net/projects/") {
			projectType = "SF";
			CG_currentProject.projectType = "SF";			
		} else {
			projectType = "CG";
			CG_currentProject.projectType = "CG";			
		}
	}
    if(projectType =="CG") {
        re = RegExp("http://code.google.com/p/.*/issues/detail\\?id=(.*)");
    } else {
        re = RegExp("http://sourceforge.net/tracker/\\?func=detail&aid=(.*)&group_id=.*&atid=.*");
    }                   
    matches = re.exec(url);
    if (matches == null) {
        return null;
    } else {
        var id = matches[1]; 
    }
    return parseInt(matches[1]);
}

////////////////////////////////////////////////////////////////////////////////
// Attempts to extract an issue ID from the supplied URL.
// If the url is not from a known issue page type then null is returned.
////////////////////////////////////////////////////////////////////////////////
function CG_getIssueAtid(url) {
    re = RegExp("http://sourceforge.net/tracker/\\?func=detail&aid=.*&group_id=.*&atid=(.*)");
    matches = re.exec(url);
    if (matches == null) {
        return null;
    } else {
        var id = matches[1]; 
    }
    return parseInt(matches[1]);
}

////////////////////////////////////////////////////////////////////////////////
// Attempts to extract the group ID from the supplied URL.
// If the url is not from a known issue page type then null is returned.
////////////////////////////////////////////////////////////////////////////////
function CG_getIssueGroupid(url) {
    re = RegExp("http://sourceforge.net/tracker/\\?func=detail&aid=.*&group_id=(.*)&atid=.*");
    matches = re.exec(url);
    if (matches == null) {
        return null;
    } else {
        var id = matches[1]; 
    }
    return parseInt(matches[1]);
}


////////////////////////////////////////////////////////////////////////////////
// An event that changes the currently selected project
////////////////////////////////////////////////////////////////////////////////
function CG_projectSelected(event){
    CG_selectProject(event.target.label);
}


////////////////////////////////////////////////////////////////////////////////
// Change the currently selected project and (optionally) load the proejct
// home page
////////////////////////////////////////////////////////////////////////////////
function CG_selectProject(project) {
  switch(typeof project) {
    case 'string':
      // we've been given a project name'
      for (i = 0; i < CG_projects.length; i++) {
        if (CG_projects[i].name == project) {
          CG_selectProject(CG_projects[i]);
          break;
        }
      }
      break;
    case 'object':
      // we've been given a project so load project 
      CG_loadHomePage(project.name);
      var projectButton = document.getElementById("selectedProject");
      projectButton.label = project.name;
      CG_currentProject = project;
      break;
  }
}

////////////////////////////////////////////////////////////////////////////////
// Loads the specified projects home page
////////////////////////////////////////////////////////////////////////////////
function CG_loadHomePage(project) {
    CG_loadURL(CG_getBaseURL(project));
}


////////////////////////////////////////////////////////////////////////////////
// Loads the specified projects default page
////////////////////////////////////////////////////////////////////////////////
function CG_loadDefaultPage(project) {
  var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  var defaultPage = prefs.getCharPref("extensions.defaultSearchPage");
  if (defaultPage == "wiki") {
    CG_loadWikiPage(project);
  } else if (defaultPage == "rcs") {
    CG_loadSVNPage(project);
  } else  if (defaultPage == "issue") {
    CG_loadIssueListPage(project);
  } else {
    alert("Unable to search, default page setting is invalid");
  }
}

////////////////////////////////////////////////////////////////////////////////
// Loads the issue page for the currently selected project.
////////////////////////////////////////////////////////////////////////////////
function CG_loadIssueListPage(event) {
    CG_loadURL(CG_getIssueListPageURL());
}

////////////////////////////////////////////////////////////////////////////////
// Get URL of issue page for the currently selected project.
////////////////////////////////////////////////////////////////////////////////
function CG_getIssueListPageURL() {
    var project = document.getElementById('selectedProject').label;
    return CG_getBaseIssueURL(project);
}

////////////////////////////////////////////////////////////////////////////////
// Loads the specified projects wiki page
////////////////////////////////////////////////////////////////////////////////
function CG_loadWikiPage(project) {
    var pageURL = gBrowser.currentURI.spec;
    var projectName = CG_getProjectName(pageURL);
    var sourceforgeName = CG_getSFName(pageURL);
    
    if (projectName != null) {
      var url = CG_getBaseURL(project) + "/w/list";
      var searchTerm = CG_getSearchTerm();
      if (searchTerm != "") {
          url = url + "?q=" + searchTerm;
      }
      CG_loadURL(url);
    }
   else if (sourceforgeName != null){
   var url = CG_getBaseURL(project) + "/w/list";
      var searchTerm = CG_getSearchTerm();
      if (searchTerm != "") {
          url = url + "?q=" + searchTerm;
      }
      CG_loadURL(url);
   }
   
   // http://sourceforge.net/apps/trac/sourceforge/wiki
}

////////////////////////////////////////////////////////////////////////////////
// Loads the specified projects svn page
////////////////////////////////////////////////////////////////////////////////
function CG_loadSVNPage(project) {
    var pageURL = gBrowser.currentURI.spec;
    var projectName = CG_getProjectName(pageURL);
    var sourceforgeName = CG_getSFName(pageURL);
    var searchTerm = CG_getSearchTerm();
    
    if (projectName != null) {
      if (searchTerm == "") {
         var url = "http://" + project + ".googlecode.com/svn/";
      } else {
         var url = "http://www.google.com/codesearch?q=" + searchTerm + "+package%3A" + project + ".googlecode.com&origq=" + project + "&btnG=Search+Trunk";
      }
      CG_loadURL(url);
    } else if (sourceforgeName != null){
      if (searchTerm == "") {
         var url = "http://" + project + ".cvs.sourceforge.net/viewvc/" + project;
      } else {
        alert("Sorry the Search facility is not available on Sourceforge.net");
        var url = "http://" + project + ".cvs.sourceforge.net/viewvc/" + project;
      }
      CG_loadURL(url);        
    }
}


////////////////////////////////////////////////////////////////////////////////
// Loads new issue page for the currently selected project
////////////////////////////////////////////////////////////////////////////////
function CG_loadNewIssuePage() {
    var project = document.getElementById('selectedProject').label;
    // if the project is a google code one load the following url
    try
    {
      if(CG_currentProject.projectType == "CG")
      { 
        var url = CG_getBaseURL(project) + "/issues/entry";
        CG_loadURL(url);
      }
      else
      {
        var projectId = CG_currentProject.id;
        var url = "http://sourceforge.net/tracker/\?func=add&group_id=" + projectId + "&atid=" + CG_currentProject.atid;
        CG_loadURL(url);
      }
    }
    catch(err) {
     alert("error is " + err);
    }
    
}

////////////////////////////////////////////////////////////////////////////////
// Loads and lists Issues using a given search type
////////////////////////////////////////////////////////////////////////////////
function CG_listIssuesBySearchType(searchType) {
    var project = document.getElementById('selectedProject').label;
    var url = CG_getBaseIssueURL(project) + "&can=" + searchType;
    CG_loadURL(url);
}

////////////////////////////////////////////////////////////////////////////////
// Loads and lists Issues considered popular. Popular issues
// are ones that have a minimum number of stars. The number
// of stars needed is defined in the toolbar options.
////////////////////////////////////////////////////////////////////////////////
function CG_listPopularIssues() {
    var project = document.getElementById('selectedProject').label;
    var url = CG_getBaseIssueURL(project);
    var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
    var minStars = prefs.getIntPref("extensions.popularIssuesRating");
    if (url.indexOf("&q") > 0) {
      url = url + " " + "stars:" + minStars;
    } else {
      url = url + "&q=stars:" + minStars;
    } 
    CG_loadURL(url);
}

////////////////////////////////////////////////////////////////////////////////
// Loads the specified URL in the browser.
////////////////////////////////////////////////////////////////////////////////
function CG_loadURL(url) {
    window._content.document.location = url;
    window.content.focus();
}

////////////////////////////////////////////////////////////////////////////////
// Get the base URL for the given project
////////////////////////////////////////////////////////////////////////////////
function CG_getBaseURL(project) {
  var baseURL;
  // we've been given a project name'
  for (i = 0; i < CG_projects.length; i++) {
    if (CG_projects[i].name == project) {
          baseURL = CG_projects[i].baseURL;
          break;
    }
  }
  return baseURL + project;
  
}

////////////////////////////////////////////////////////////////////////////////
// Get the base URL for the issue page of a given project
// The URL will include search and sort settings
////////////////////////////////////////////////////////////////////////////////
function CG_getBaseIssueURL(project) {
    var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  
    var url = CG_getBaseURL(project) + "/issues/list?sort=";
    if (prefs.getBoolPref("extensions.issueSortMilestone")) {
	      url = url + "milestone+";
    }
    if (prefs.getBoolPref("extensions.issueSortPriority")) {
      url = url + "priority+";
    }
    if (prefs.getBoolPref("extensions.issueSortOwner")) {
      url = url + "owner+";
    }
    if (prefs.getBoolPref("extensions.issueSortType")) {
      url = url + "type+";
    }
    if (prefs.getBoolPref("extensions.issueSortStatus")) {
      url = url + "status+";
    }
    url = url + "id";
    
    var searchTerm = CG_getSearchTerm();
    if (searchTerm != "") {
        url = url + "&q=" + searchTerm;
    }
    return url;
}

////////////////////////////////////////////////////////////////////////////////
// Get the current search term as entered in the text box
////////////////////////////////////////////////////////////////////////////////
function CG_getSearchTerm() {    
    var textInput = document.getElementById("textInput");
    return textInput.value;
} 

////////////////////////////////////////////////////////////////////////////////
// String utilities
////////////////////////////////////////////////////////////////////////////////
// Removes leading whitespaces
function CG_lTrim( value ) {
    var re = /\s*((\S+\s*)*)/;
    return value.replace(re, "$1");
}

// Removes ending whitespaces
function CG_rTrim( value ) {
    var re = /((\s*\S+)*)\s*/;
    return value.replace(re, "$1");
}

// Removes leading and ending whitespaces
function CG_trim( value ) {	
    return CG_lTrim(CG_rTrim(value));
    
}

////////////////////////////////////////////////////////////////////////////////
// Searches the currently loaded Sourceforge project's tracker with the 
// current search term.
////////////////////////////////////////////////////////////////////////////////
function CG_searchTrackerSourceForge() {
  //get SF id for project 
  var SFiD = CG_currentProject.id;
  // get search terms from user
  var searchTerm = CG_getSearchTerm();  
  // Load URL for the tracker search with keyword(s) from the search box
      if (searchTerm != "") {
       var url = "http://sourceforge.net/search/?type_of_search=artifact&group_id=" + SFiD + "&words=" + searchTerm;
          
      } else {
       var url = "http://sourceforge.net/search/?type_of_search=artifact&group_id=" + SFiD + "&words=";
      }
      CG_loadURL(url);
}


////////////////////////////////////////////////////////////////////////////////
// Searches the currently loaded Sourceforge project's Forum with the current 
// search term.
////////////////////////////////////////////////////////////////////////////////
function CG_searchForumSourceForge() {
  //get SF id for project 
  var SFiD = CG_currentProject.id;
  var searchTerm = CG_getSearchTerm();  
  // load URL for the forum search with keyword(s) from the search box
      if (searchTerm != "") {
       var url = "http://sourceforge.net/search/index.php?group_id=" + SFiD + "&form_submit=Search&search_subject=1&search_body=1&type_of_search=forums&all_words=" + searchTerm + "&exact_phrase=&some_word=&without_words=&posted_by=&posted_date_start=&posted_date_end=";   
      } else {
       var url = "http://sourceforge.net/search/index.php?group_id=" + SFiD + "&form_submit=Search&search_subject=1&search_body=1&type_of_search=forums&all_words=&exact_phrase=&some_word=&without_words=&posted_by=&posted_date_start=&posted_date_end=";      }
      CG_loadURL(url);  
}

////////////////////////////////////////////////////////////////////////////////
// Searches the currently loaded Sourceforge project's Mailing List with the 
// current search term. 
////////////////////////////////////////////////////////////////////////////////
function CG_searchMailingListSourceForge() {
  //get SF id for project 
  var SFiD = CG_currentProject.id;
  //change static SFiD ref to something like CG_currentProject.baseURL
  var searchTerm = CG_getSearchTerm();  
  // load url for the mailing list search with keyword(s) from the search box
      if (searchTerm != "") {
       var url = "http://sourceforge.net/search/index.php?group_id=" + SFiD + "&form_submit=Search&search_subject=1&search_body=1&type_of_search=mlists&all_words=" + searchTerm + "&exact_phrase=&some_word=&without_words=&posted_by=&posted_date_start=&posted_date_end=";   
      } else {
       var url = "http://sourceforge.net/search/index.php?group_id=" + SFiD + "&form_submit=Search&search_subject=1&search_body=1&type_of_search=mlists&all_words=&exact_phrase=&some_word=&without_words=&posted_by=&posted_date_start=&posted_date_end=";      }
      CG_loadURL(url);  
}

////////////////////////////////////////////////////////////////////////////////
// Searches the currently loaded Sourceforge project's Documentation 
// with the current search term.
////////////////////////////////////////////////////////////////////////////////
function CG_searchDocsSourceForge() {
  var SFiD = CG_currentProject.id;
  var searchTerm = CG_getSearchTerm();  
  // load URL for the Documentation search with keyword(s) from the search box.
      if (searchTerm != "") {
       var url = "http://sourceforge.net/search/index.php?group_id=" + SFiD + "&form_submit=Search&search_subject=1&search_body=1&type_of_search=docs&all_words=" + searchTerm + "&exact_phrase=&some_word=&without_words=&posted_by=&posted_date_start=&posted_date_end=";   
      } else {
       var url = "http://sourceforge.net/search/index.php?group_id=" + SFiD + "&form_submit=Search&search_subject=1&search_body=1&type_of_search=docs&all_words=&exact_phrase=&some_word=&without_words=&posted_by=&posted_date_start=&posted_date_end=";      }
      CG_loadURL(url);  
}

///////////////////////////////////////////////////////////////////////////////////
// Create a doap for the current project, currently only works for Google projects
///////////////////////////////////////////////////////////////////////////////////
function CG_createDoap(doapProject) {
  try{
    if(CG_currentProject.name == doapProject) {
      doapProject = CG_currentProject;
    }
    if (doapProject.baseURL != "http://code.google.com/p/") {
      alert("Sorry DOAP files are only created for Google projects at present.");
      return;
    }
    var pageURL = gBrowser.currentURI.spec;
    //must check you are on the home page of loaded project when doap is created
    if(pageURL == CG_getBaseURL(doapProject.name)+"/" && CG_getBaseURL(doapProject.name) == "http://code.google.com/p/" + doapProject.name) {
      description = CG_getDescription();
      shortdescription = CG_getShortDescription();
      wikiURL = CG_getBaseURL(doapProject.name) + "/w/list";
      var bugURL = CG_getBaseURL(doapProject.name) + "/issues/list";
      var mailingListURL = "http://groups.google.com/group/" + doapProject.name + "-users";    //example http://groups.google.com/group/codegoo-users
      var license = CG_getLicense();
      var licenseURI = CG_getURLLicense();
      var downloadURL = CG_getBaseURL(doapProject.name) + "/downloads/list";
      var maintainer = new Array();
      var maintainerURI = new Array();
      maintainer = CG_getMaintainerID(); 
      var maintainerURI = CG_getMaintainerURI(); 
      var developer = new Array();
      var developerURI = new Array();
      developer = CG_getDeveloperID();
      developerURI = CG_getDeveloperURI();
      var mailingListURL = new Array(); 
      mailingListURL = CG_getGroups();
      if(doapProject.Xml){
        doapProject.Xml(description, shortdescription, doapProject.baseURL + doapProject.name, wikiURL, bugURL, mailingListURL, licenseURI, license, downloadURL, maintainer, maintainerURI, developer, developerURI);
      } else {
        try {          
          doapProject = new Project(CG_currentProject.name, CG_currentProject.baseURL, CG_currentProject.id, CG_currentProject.projectType);
          // if any issues saved you must copy these over to new Project and save in prefs
          if(CG_currentProject.issues != null) {
            doapProject.issues = CG_currentProject.issues;
          }
          doapProject.Xml(description, shortdescription, doapProject.baseURL + doapProject.name, wikiURL, bugURL, mailingListURL, licenseURI, license, downloadURL, maintainer, maintainerURI, developer, developerURI);
        } catch (e) {
          alert("error" + e);
        }   
      }
      CG_saveToFile(doapProject.doapxml, doapProject.name);
      CG_currentProject = doapProject;
      for(i=0; i < CG_projects.length; i++) {
        if (CG_projects[i].name == doapProject.name) {
          CG_projects[i] = doapProject; 
          CG_saveProjects(); 
        }    
      }        
    } else {
      conf = confirm("You must be on the home page of a Google project to create a DOAP. Do you want to go to the home page now?")
      alert(conf);
      if(conf == true) { 
        //load homepage
        CG_loadHomePage(doapProject.name);
        CG_createDoap(doapProject);
      }
    }
  } catch(err) {
    alert("error is " + err + " " + doapProject.toSource());
  }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// gets groups href information (URL for mailing lists) for current project from home page currently works only on Google
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function CG_getGroups() {
  var groups = new Array();
  var groupsTag = window._content.document.getElementById("group_links");
  if(groupsTag != null) {
  var counter = 0;
    for (var i = 0; i < groupsTag.childNodes.length ; i++) {     
      if(groupsTag.childNodes[i].tagName == "LI") {
        var href = groupsTag.childNodes[i].firstChild.getAttribute("href");
        groups[counter] = href;
        counter++;
      }
    }  
  }
  return groups;
}

/////////////////////////////////////////////////////////////////////////////////////////////////
// gets description information for current project from home page currently works only on Google
/////////////////////////////////////////////////////////////////////////////////////////////////
function CG_getDescription() {
  var descriptionDoap = "";
  var wikiContent = window._content.document.getElementById("wikicontent");
  for (var i = 0; i < wikiContent.childNodes.length ; i++) {  
    if(wikiContent.childNodes[i].firstChild != null){
      for (var ind = 0; ind < wikiContent.childNodes[i].childNodes.length; ind++) {
        if(wikiContent.childNodes[i].childNodes[ind].tagName != "STYLE" && wikiContent.childNodes[i].childNodes[ind].tagName != "SCRIPT")
        if( wikiContent.childNodes[i].childNodes[ind].nodeValue != null) {
          descriptionDoap += wikiContent.childNodes[i].childNodes[ind].nodeValue;
        }
        if(wikiContent.childNodes[i].childNodes[ind].hasChildNodes()) {     
          descriptionChild = wikiContent.childNodes[i].childNodes[ind];           
          for(var z =0; z < descriptionChild.childNodes.length; z++) {
            if(descriptionChild.hasChildNodes() && descriptionChild.childNodes[z].nodeValue != null && descriptionChild.tagName != "STYLE" && descriptionChild.tagName != "SCRIPT") {
              descriptionDoap += descriptionChild.childNodes[z].nodeValue;
            }
            if(descriptionChild.childNodes[z].hasChildNodes()){
              for(var y =0; y < descriptionChild.childNodes[z].childNodes.length; y++) {
                if(descriptionChild.childNodes[z].childNodes[y].nodeValue != null) {
                  descriptionDoap += descriptionChild.childNodes[z].childNodes[y].nodeValue;
                }
                if(descriptionChild.childNodes[z].childNodes[y].hasChildNodes()){
                  for(var x =0; x < descriptionChild.childNodes[z].childNodes[y].childNodes.length; x++) {
                    if(descriptionChild.childNodes[z].childNodes[y].childNodes[x].nodeValue != null) {
                      descriptionDoap += descriptionChild.childNodes[z].childNodes[y].childNodes[x].nodeValue;
                    }
                    if(descriptionChild.childNodes[z].childNodes[y].childNodes[x].hasChildNodes()){
                      if(descriptionChild.childNodes[z].childNodes[y].childNodes[x].firstChild.nodeValue != null) {
                        descriptionDoap += descriptionChild.childNodes[z].childNodes[y].childNodes[x].firstChild.nodeValue;
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
  return descriptionDoap;
} 

//////////////////////////////////////////////////////////////////////////////////////////////////
// gets short description information for current project, works on Google projects only at present
//////////////////////////////////////////////////////////////////////////////////////////////////
function CG_getShortDescription() {
  var shortDescription;
  var projectSummaryTag = window._content.document.getElementById("project_summary_link");
  shortDescription = projectSummaryTag.childNodes[0].nodeValue;
  return shortDescription;
}

/////////////////////////////////////////////////////////////////////////////////////////
//  gets URL license information for current project, works on Google projects only at present
/////////////////////////////////////////////////////////////////////////////////////////
function CG_getURLLicense() {
  var license = "";
  var licenseURL = "";
  var aTagName = window._content.document.getElementsByTagName("a");
  for (var i = 0; i < aTagName.length ; i++) {
    var y = aTagName[i].childNodes[0];
    re = RegExp("(.*License.*)");
    matches = re.exec(y.nodeValue);
    if (matches != null) {
      license = matches[1]; 
      // get html attribute from this license tag
      licenseURL = aTagName[i].getAttribute('href');      
    }       
  }
  return licenseURL;
}

/////////////////////////////////////////////////////////////////////////////////////////
//  gets license information for current project, works on Google projects only at present
/////////////////////////////////////////////////////////////////////////////////////////
function CG_getLicense() {
  var license = "";
  var aTagName = window._content.document.getElementsByTagName("a");
  for (var i = 0; i < aTagName.length ; i++) {
    var y = aTagName[i].childNodes[0];
    re = RegExp("(.*License.*)");
    matches = re.exec(y.nodeValue);
    if (matches != null) {
      license = matches[1]; 
    }       
  }
  return license;
}

///////////////////////////////////////////////////////////////////////////////////////////
// gets maintainer information for current project works on Google projects only at present
///////////////////////////////////////////////////////////////////////////////////////////
function CG_getMaintainerID() {
  var maintainers  = new Array();
  var ownersTag = window._content.document.getElementById("owners");
  if(ownersTag != null) {
    var ownerTagChild = ownersTag.childNodes[1];
    maintainers[0] = ownerTagChild.childNodes[0].nodeValue;
    var i = 3;
    var a = 1;
    while(ownersTag.childNodes[i] != null) {
      maintainers[a] = ownersTag.childNodes[i].childNodes[0].nodeValue;
      i = i + 2; 
      a++;
    }        
  }
  return maintainers;
}

///////////////////////////////////////////////////////////////////////////////////////////
// gets maintainer URI information for current project works on Google projects only at present
///////////////////////////////////////////////////////////////////////////////////////////
function CG_getMaintainerURI() {
  var maintainersURI  = new Array();
  var ownersTag = window._content.document.getElementById("owners");
  if(ownersTag != null) {
    var ownerTagChild = ownersTag.childNodes[1];
    maintainersURI[0] = CG_GOOGLECODE_URL + ownerTagChild.getAttribute('href'); 
    var i = 3;
    var a = 1;
    while(ownersTag.childNodes[i] != null) {
      maintainersURI[a] = CG_GOOGLECODE_URL + ownersTag.childNodes[i].getAttribute('href'); 
      i = i + 2; 
      a++;
    }        
  }
  return maintainersURI;
}
///////////////////////////////////////////////////////////////////////////////////////////
// gets maintainer information for current project works on Google projects only at present
///////////////////////////////////////////////////////////////////////////////////////////
function CG_getDeveloperID() {
  var developers = new Array();
  var membersTag = window._content.document.getElementById("members");
  if(membersTag != null) {
    var memberTagChild = membersTag.childNodes[1];
    developers[0] = memberTagChild.childNodes[0].nodeValue;
    var i = 3;
    var a = 1;
    while(membersTag.childNodes[i] != null) {
      developers[a] = membersTag.childNodes[i].childNodes[0].nodeValue;
      i = i + 2; 
      a++;
    }    
  }
  return developers;
}

///////////////////////////////////////////////////////////////////////////////////////////
// gets maintainer URI information for current project works on Google projects only at present
///////////////////////////////////////////////////////////////////////////////////////////
function CG_getDeveloperURI() {
  var developersURI = new Array();
  var membersTag = window._content.document.getElementById("members");
  if(membersTag != null) {
    var memberTagChild = membersTag.childNodes[1];
    developersURI[0] = CG_GOOGLECODE_URL + memberTagChild.getAttribute('href'); 
    var i = 3;
    var a = 1;
    while(membersTag.childNodes[i] != null) {
      developersURI[a] = CG_GOOGLECODE_URL + membersTag.childNodes[i].getAttribute('href'); 
      i = i + 2; 
      a++;
    }    
  }
  return developersURI;
}

///////////////////////////////////////////////////////////////////////////////////////////
// saves content to a file on hard disk
// Code in this method was inspired (even copied) from https://developer.mozilla.org/Project:Copyrights
// original code is available from that site under the MIT licence
///////////////////////////////////////////////////////////////////////////////////////////
function CG_saveToFile(content, name){
  var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
  // get the path to the user's home (profile) directory
  const DIR_SERVICE = new Components.Constructor("@mozilla.org/file/directory_service;1","nsIProperties");
  try { 
    path=(new DIR_SERVICE()).get("ProfD", Components.interfaces.nsIFile).path; 
  } catch (e) {
    alert("error");
  }
  // determine the file-separator
  if (path.search(/\\/) != -1) {
    path = path + "\\";
  } else {
    path = path + "/";
  }
  var savefile = "doap.xml";
  if (name != null) {
    var currentProject = name;
    savefile = currentProject + ".xml";
  }
  savefile = path+savefile;
  //alert("DOAP file path is " + savefile);
  file.initWithPath(savefile);

  // file is nsIFile, data is a string
  var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);

 
  // use 0x02 | 0x10 to open file for appending.
  foStream.init(file, 0x02 | 0x08 | 0x20, 420, 0); 
  // write, create, truncate
  // In a c file operation, we have no need to set file mode with or operation,
  // directly using "r" or "w" usually.

  // if you are sure there will never ever be any non-ascii text in data you can 
  // also call foStream.writeData directly
  var converter = Components.classes["@mozilla.org/intl/converter-output-stream;1"].createInstance(Components.interfaces.nsIConverterOutputStream);
  converter.init(foStream, "UTF-8", 0, 0);
  converter.writeString(content);
  converter.close(); // this closes foStream
  if ( file.exists() == false ) {
    alert("File does not exist " + savefile);
  }
}

/////////////////////////////////////////////////////////////////////////////////
//Submit doap to a Simal instance
////////////////////////////////////////////////////////////////////////////////
function CG_submitDoapToSimal(){
	if (CG_currentProject.baseURL == "http://code.google.com/p/") {
	  doapXML = CG_currentProject.doapxml;
	  makePOSTRequest("http://localhost:8080/simal-rest/addProject", "rdf=" + doapXML);
	} else {
	  alert("Sorry DOAP files are only created for Google projects at present.");
	}
}

/////////////////////////////////////////////////////////////////////////////////
// Make and send an HTTP POST request
/////////////////////////////////////////////////////////////////////////////////
var http_request = false;
function makePOSTRequest(url, parameters) {
   http_request = false;
   if (window.XMLHttpRequest) { // Mozilla, Safari,...
      http_request = new XMLHttpRequest();
      if (http_request.overrideMimeType) {
      	// set type accordingly to anticipated content type
        http_request.overrideMimeType('text/xml');
        //http_request.overrideMimeType('text/html');
      }
   } else if (window.ActiveXObject) { // IE
      try {
         http_request = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
         try {
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (e) {}
      }
   }
   if (!http_request) {
      alert('Cannot create XMLHTTP instance');
      return false;
   }
   
   http_request.onreadystatechange = CG_loadHomePage;
   http_request.open('POST', url, true);
   http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   http_request.setRequestHeader("Content-length", parameters.length);
   http_request.setRequestHeader("Connection", "close");
   http_request.send(parameters);
}

/////////////////////////////////////////////////////////////////////////////////
// show doap to user
////////////////////////////////////////////////////////////////////////////////
function CG_viewDoap(name){
  if (CG_currentProject.baseURL == "http://code.google.com/p/") {
    try{
      var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
      if (name != null) {
        var currentProject = name;
        savedfile = currentProject + ".xml";
      } 
	  // get the path to the user's home (profile) directory
      const DIR_SERVICE = new Components.Constructor("@mozilla.org/file/directory_service;1","nsIProperties");       
      path=(new DIR_SERVICE()).get("ProfD", Components.interfaces.nsIFile).path; 
      // determine the file-separator
      if (path.search(/\\/) != -1) {
        path = path + "\\";
      } else {
        path = path + "/";
      }
      savedfile = path+savedfile;     alert("DOAP file path is " + savedfile + "\n\nDOAP is:\n\n" + CG_currentProject.doapxml);
    } catch (e){
      alert(e);
    }
  } else {
    alert("Sorry DOAP files are only created for Google projects at present.");
  }
}